<?php
$bool_IE = false;

if( strpos( $_SERVER["HTTP_USER_AGENT"], "MSIE" ) !== false ) $bool_IE = true;

function category_multi_level($sParent, $sprefix = "",$i_selected_item, $arr_data) {
    //if($sParent == NULL)
    //    $arr_data = $this->arr_data;
    $arr_temp = array();
    foreach ( $arr_data as $key => $o_modelTemp) {
        if($o_modelTemp->parent == $sParent) {
            array_push($arr_temp, $o_modelTemp);
        }
    }

    foreach ( $arr_temp as $key => $o_modelTemp) {

        if($o_modelTemp->identification == $i_selected_item)
            echo "<option value='".$o_modelTemp->identification."' selected='selected'>".$sprefix.$o_modelTemp->name."</option>";
        else
            echo "<option value='".$o_modelTemp->identification."'>".$sprefix.$o_modelTemp->name."</option>";

        category_multi_level($o_modelTemp->identification,$sprefix."....",$i_selected_item, $arr_data);
    }
}
?>


<div class="clear"></div>

<div class="border_box">

    <?php
    if ( isset($s_errMsg) && $s_errMsg != '') {
        echo "<p>".$s_errMsg."</p>";
        exit;
    }?>
    <div class="form_header">
        <input
            id         = "btn_productDisp"
            name       = "btn_productDisp"
            type       = "button"
            value      = "Sản Phẩm"
            class      = "button button_css3"
            onclick    = "setProductMultiImageSector(1)"
        />
    
        <input
            id         = "btn_multiImageDisp"
            name       = "btn_multiImageDisp"
            type       = "button"
            value      = "Tải Ảnh Sản Phẩm"
            class      = "button button_css3"
            onclick    = "setProductMultiImageSector(2)"
        />
    </div>

    <form class="form_input" action="" method="post" id="form_item" name="form_item">
        <fieldset class="border_radius_all" id="fieldset_product">
            <legend></legend>

            <div class="form_input_row">
                <label class="label_title">Sản Phẩm:*</label>
                <input
                    id          = "txt_subject"
                    name        = "txt_subject"
                    title       = "Tên Sản Phẩm"
                    type        = "text"
                    value       = "<?php if(isset($o_model)) { echo $o_model->subject;}?>"
                    class       = "form_textbox textbox_css3"
                    tabindex    = "1"
                    onblur      = "validation_onblur(this,'lbl_subject_validation')"
                />
                <label
                    id       = "lbl_subject_validation" 
                    class    = "lable_validation"
                >Bạn chưa nhập tên sản phẩm.</label>
            </div><!--End form_input_row Name-->
            
            <div class="form_input_row">
                <label class="label_title">URL Ảo:*</label>
                <input
                    id          = "txt_url"
                    name        = "txt_url"
                    title       = "URL Ảo"
                    type        = "text"
                    value       = "<?php if(isset($o_model)) { echo $o_model->url_mapping;}?>"
                    class       = "form_textbox textbox_css3"
                    tabindex    = "2"
                    onblur      = "validation_onblur(this,'lbl_url_validation')"
                />
                <label
                    id       = "lbl_url_validation"
                    class    = "lable_validation"
                >Bạn chưa nhập url ảo.</label>
            </div><!--End form_input_row Name-->
            
            <div class="form_input_row">
                <label class="label_title">Danh Mục:*</label>
                
                <select 
                    id      = "sl_category"
                    name    = "sl_category"
                    tabindex= "3"
                    <?php
                    if ($bool_IE != true)
                        echo "class = 'form_combobox select_css3 select_two_arrown'";
                    else
                        echo "class = 'form_combobox'";
                    ?>
                >
                    <?php
                    if(isset($o_model))
                        category_multi_level($sParent = 0, $sprefix = "",$o_model->category,$arr_data);
                    else
                        category_multi_level($sParent = 0, $sprefix = "",0,$arr_data);
                    ?>
                </select>
            </div><!--End form_input_row-->

            <div class="form_input_row">
                    <label class="label_title">Giá Tiền:*</label>
                    <input
                        id          = "txt_price"
                        name        = "txt_price"
                        title       = "Giá Tiền"
                        type        = "text"
                        value       = "<?php if(isset($o_model)) { echo $o_model->price;}?>"
                        class       = "form_textbox textbox_css3"
                        tabindex    = "4"
                        onblur      = "validation_onblur(this,'lbl_price_validation')"
                        onkeyup     = "this.value=format_currency(this.value);"
                    />
                    <label
                        id        = "lbl_price_validation"
                        class    = "lable_validation"
                    >Bạn chưa nhập giá tiền.</label>
                </div><!--End form_input_row Name-->
                
                <div class="form_input_row">
                    <label class="label_title">Có VAT:</label>
                    <div class="input_items_horizon">
                        <input
                            id          = "chk_vat"
                            name        = "chk_vat"
                            title       = "Có VAT"
                            type        = "checkbox"
                            tabindex    = "5"
                            value       = "1"
                            <?php if( isset($o_model) && $o_model->vat == 1) { echo "checked='checked'";}?>
                        />
                    </div>
                </div><!--End form_input_row Name-->

            <div class="form_input_row">
                <label class="label_title"> </label>
                <img alt="preview" src="<?php if(isset($o_model)) { echo $o_model->image;}?>" class="image_preview" id="img_preview">
                <div class="input_items_horizon" id="div_imageUpload">
                    <input
                        id          = "txt_image"
                        name        = "txt_image"
                        title       = "Hình ảnh đại diện danh mục"
                        type        = "text"
                        value       = "<?php if(isset($o_model)) { echo $o_model->image;}?>"
                        class       = "form_textbox textbox_css3"
                        tabindex    = "6"
                        style       = "width: 99%;"
                    /><br/><br/>
                    <input
                        type    = "checkbox"
                        id      = "chk_image"
                        name    = "chk_image"
                        onchange= "visible_uploadbox();"
                    /> Upload hình lên máy chủ.
                </div>
                
            </div><!--End form_input_row-->
            <div class="clear"></div>
            
            <div class="form_input_row">
                <div class="title_full"> <strong>Mô Tả:</strong></div>
                <textarea
                    id      = "ta_description"
                    name    = "ta_description"
                    rows    = "10"
                    cols    = "40"
                    tabindex="7"
                ><?php if(isset($o_model)) { echo $o_model->description;}?></textarea>
            </div><!--End form_input_row-->
            
            <div class="form_input_row">
                <div class="title_full"> <strong>Nội Dung:</strong></div>
                <textarea
                    id      = "ta_content"
                    name    = "ta_content"
                    rows    = "200"
                    cols    = "40"
                    tabindex="8"
                ><?php if(isset($o_model)) { echo $o_model->content;}?></textarea>
            </div><!--End form_input_row-->
        </fieldset>

        <fieldset class="border_radius_all" id="fieldset_multiImageUploading">
            <legend></legend>

            <div class="form_input_row">
                <label class="label_title"> </label>

                <div class="input_items_horizon" id="div_addMultiURLImage">
                    <textarea
                        id      = "ta_nultiImage"
                        name    = "ta_nultiImage"
                        class   = "form_textarea textarea_css3"
                        style   = "width: 99.4%"
                        rows    = "10"
                    ></textarea>

                    <div class="clear"></div>
                    <br />

                    <input
                        title       = "Thêm Hình"
                        name        = "btn_addMultiURLImage"
                        id          = "btn_addMultiURLImage"
                        type        = "button"
                        value       = "Thêm Hình"
                        class       = "input_button button_css3"
                    />
                </div>

                <div class="input_items_horizon" id="div_addMultiImage">
                    <input 
                        type        = "file"
                        id          = "file_MultiImage"
                        name        = "file_MultiImage"
                        class       = "form_textbox textbox_css3" 
                        style       = "width: 99%;"
                        accept      = "image/*" 
                        multiple    = "true"
                    />
                </div>

                <div class="input_items_horizon">
                    <input
                        type        = "checkbox"
                        id          = "chk_Multiimage"
                        name        = "chk_Multiimage"
                        onchange    = "visible_uploadMultibox();"
                    /> Upload url (đường dẫn) của hình ảnh.
                </div>
            </div><!--End form_input_row-->
            
            <div class="clear"></div>

            <div class="box_content_no_border" id="div_contentBox" style="float:left;width: 99.5%;">
                <div class="galleries_item border_box" id="div_galleriesImage">

                    <?php foreach ($arr_proImage as $index=>$o_proImage){?>
                    <div class = "item_vertical" id="div_proImage<?=$o_proImage->key;?>">
                        <img alt = "<?=$o_proImage->name;?>" src = "<?=$o_proImage->url;?>" />
    
                        <div class="item_content border_radius_all">
                            <input 
                                id       = "btn_delete"
                                name     = "delete"
                                type     = "button"
                                value    = "Xóa"
                                style    = "width:100%;"
                                class    = "button button_css3"
                                onclick  = "delete_selectedItem('div_proImage<?=$o_proImage->key;?>', 2, <?=$o_proImage->key;?>)" 
                            />
                            <span></span>
                        </div>
                    </div><!-- End item_vertical -->
                    <?php }//End foreach?>

                </div><!-- End galleries_item -->
            </div><!--End box_content_no_border-->

        </fieldset>

        <fieldset>
            <div class="form_input_row" style="border: none;">
                <div class="input_items_horizon">
                    <input
                        title       = "gửi yêu cầu"
                        name        = "btn_save"
                        id          = "btn_save"
                        type        = "submit"
                        value       = "Lưu"
                        class       = "input_button button_css3"
                        tabindex    = "9"
                    />
                    <input
                        title       = "gửi yêu cầu"
                        name        = "btn_cancel"
                        id          = "btn_cancel"
                        type        = "button"
                        value       = "Hủy Bỏ"
                        class       = "input_button button_css3"
                        tabindex    = "10"
                    />
                </div><!--End input_items_horizon-->
            </div><!--End form_input_row button-->
        </fieldset>
    </form>

</div><!--End box_950-->

<script type="text/javascript">

//Count amount of images of product
//in upload multi-images
var i_imgCount = 0;

var ta_description, ta_content, html = '';

$(document).ready(function () {

    ta_description = CKEDITOR.replace( 'ta_description', {
        toolbar: [
              ['Source'],
            [ 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ],
            [ 'FontSize', 'TextColor', 'BGColor' ],
            [ 'UIColor' ]
        ]
    }, html);

    ta_content = CKEDITOR.replace( 'ta_content', {}, html);

    $("#txt_name").focus();
    $("#div_addMultiURLImage").hide();
    $("#fieldset_multiImageUploading").hide();

    $("#file_MultiImage").uploadify({
        "formData" : {
            "timestamp"    : "<?=time();?>",
            "token"        : "<?=md5('unique_salt'.time());?>"
        },
        "buttonClass"      : "input_button button_css3",
        "swf"              : "<?=Yii::app()->baseUrl.'/assets/tool/uploadify/';?>uploadify.swf",
        "uploader"         : "<?=Yii::app()->createUrl("product/UploadMultiImage");?>",
        "onUploadSuccess"  : function(file, data, response)
        {
            if( response == true )
            {
                var arr_result = $.parseJSON(data);

                if(arr_result.error != null){
                    alert(arr_result.error);
                    return;
                }

                var s_urlImage    = "<?=Yii::app()->baseUrl;?>/"+arr_result.result;
                var i_indexChar   = s_urlImage.lastIndexOf("/");
                var s_imageName   = s_urlImage.substr( i_indexChar+1, s_urlImage.length);
                add_ImageToPrepareArea(s_urlImage, s_imageName, 2);
            }//End if
        }//End onUploadSuccess
    });
});//End $(document).ready(function ()


/* ==================================================
* @Method:    setProductMultiImageSector
* @Describe:  display upload fieldset product and multi-image
* 
* @return:    void
* =================================================== */
function setProductMultiImageSector(i_fieldset)
{
    // i_fieldset have below values
    // 1: fieldset_product
    // 2: fieldset_multiImageUploading
    if( i_fieldset == 1 )
    {
        $("#fieldset_multiImageUploading").hide();
        $("#fieldset_product").show();
    }
    else if ( i_fieldset == 2 )
    {
        $("#fieldset_multiImageUploading").show();
        $("#fieldset_product").hide();
    }
    else
        alert("Giá trị truyền vào đã bị sửa lại, xin hãy nhấn F5 để tải lại trang web");
}//End visible_uploadbox


/* ==================================================
* @Method:    visible_uploadbox
* @Describe:  display upload image upload or
*             url of main image of product
* 
* @return:    void
* =================================================== */
function visible_uploadbox(){
    if(document.getElementById("chk_image").checked==true){

        var ct      ="<input type='file' id='file_image' name='file_image' class='form_textbox textbox_css3' style = 'width: 99%;' accept='image/*' onchange='ajaxFileUpload();'/><br/><br/>";
        ct         += "<input type='checkbox' id='chk_image' onchange='visible_uploadbox();' checked='checked' />";
        document.getElementById("div_imageUpload").innerHTML= ct;
        
    } else{

        var ct      = "<input id= 'txt_image'    type= 'text' name= 'txt_image' value= '<?php if(isset($o_model)) { echo $o_model->image;}?>'    class='form_textbox textbox_css3' style = 'width: 99%;'/><br/><br/>";
        ct         += "<input type='checkbox' id='chk_image' onchange='visible_uploadbox();'/> Upload hình lên máy chủ";
        document.getElementById("div_imageUpload").innerHTML= ct;
    }
}


/* ==================================================
* @Method:    $('#btn_cancel').click()
* @Describe:  close editting dialog when user edit a record 
* 
* @return:    void
* =================================================== */
$('#btn_cancel').click(function() {

    $("#dialog_notice").dialog("close");

    var i_key     = <?=$i_key ?>;
    if(i_key != 0)
        $("#tr_"+i_key).css("background-color","#FFFFFF");
});


/* ==================================================
* @Method:    validation_onblur
* @Describe:  display error of input
*             when user forget fill value
* 
* @return:    void
* =================================================== */
function validation_onblur( element, lbl_validation) {
    
    if( element.value == ""){
        $('#'+lbl_validation).fadeIn("slow", "linear");
        //$(element).focus();
    } else {
        $('#'+lbl_validation).fadeOut();
    }
}


/* ==================================================
* @Method:    $('#txt_subject').blur()
* @Describe:  set mapping url when item name is set
* 
* @return:    void
* =================================================== */
$('#txt_subject').blur(function(){
    var str = remove_utf8(this.value.toLowerCase());
    //alert(str);
    var special_character    = " ,@!/-#%&";//unavailable:$^*()
    for(var i = 0; i < special_character.length;i++){
        str = str.replace(new RegExp(special_character.charAt(i), 'g'),"-");
    }

    $('#txt_url').val(str);
});


/* ==================================================
* @Method:    form_onsubmit
* @Describe:  check validate before submit
* 
* @return:    void
* =================================================== */
function form_onsubmit(param)
{
    if ( $("#txt_subject").val() == "" || $("#txt_subject").val().length < 4 )
    {
        $("#lbl_subject_validation").fadeIn("slow", "linear");
        $("#txt_subject").focus();
        return false;
    }

    if ( $("#txt_url").val() == "" || $("#txt_url").val().length < 4)
    {
        $("#lbl_url_validation").fadeIn("slow", "linear");
        $("#txt_url").focus();
        return false;
    }

    return true;
}


/* ==================================================
* @Method:    $("#form_item").submit()
* @Describe:  check validate before submit
* 
* @return:    void
* =================================================== */
//attach a submit handler to the form
$("#form_item").submit(function(event) {
    
    //stop form from submitting normally
    event.preventDefault();
    
    var bool_submit = form_onsubmit("form_item");
    if (bool_submit == true) {

        $( "#dialog_excute" ).dialog( "open" );
        var i_key = <?=$i_key ?>;
        var url_image = $("#img_preview").attr("src");

        if( typeof $("#txt_image").val() !="undefined" &&
            $("#txt_image").val() != ""
        )
            url_image = $("#txt_image").val();

        var arr_imgUrls = $("img[name='img_upload']").map(function() {
            return this.src;
        }).get();

        var arr_imgNames = $("img[name='img_upload']").map(function() {
            return this.alt;
        }).get();

        $.ajax({
            url            : "<?=Yii::app()->createUrl("product/save");?>",
            type           : "POST",
            contentType    : "application/x-www-form-urlencoded; charset=UTF-8",
            cache          : false,
            data           : {
                item_key          : i_key,
                txt_subject       : $("#txt_subject").val(),
                sl_category       : $("#sl_category").val(),
                txt_urlMapping    : $("#txt_url").val(),
                txt_image         : url_image,
                chk_vat           : ($("#chk_vat").is(':checked')? 1 : 0),
                ta_description    : ta_description.getData(),
                ta_content        : ta_content.getData(),
                arr_imgUrl        : arr_imgUrls,
                arr_imgName       : arr_imgNames
            },
            success : function(string){

                /**
                 * Kiểu mặc định trả về là dạng String, bạn dùng hàm parseJSON để phân tích dữ liệu trả về
                 * có 2 cách parse JSON là : JSON.parse() và $.parseJSON();
                 * 1. var getData = JSON.parse(string);
                 * 2. var getData = $.parseJSON(string);
                **/
                var arr_result = $.parseJSON(string);
                if(arr_result.error != null){
                    alert(arr_result.error);
                    $("#dialog_excute").dialog("close");
                    return;
                }

                var ct_row = "";

                if(i_key != 0) 
                {
                    ct_row += "<td>";
                    ct_row += "    <input";
                    ct_row += "        id       = 'chk_delete'";
                    ct_row += "        name     = 'chk_delete'";
                    ct_row += "        type     = 'checkbox'";
                    ct_row += "        class    = 'check_box'";
                    ct_row += "        value    = '"+ arr_result.key +"'";
                    ct_row += "        onclick='display_button(this);'";
                    ct_row += "    />";
                    ct_row += "</td>";
                    
                    ct_row += "<td>";
                    ct_row += "    <span";
                    ct_row += "        class      = 'icon_button icon_edit'";
                    ct_row += "        onclick    = \"call_edit_page("+ arr_result.key +");\"";
                    ct_row += "    > ";
                    ct_row += "    </span>";
                    ct_row += "</td>";
                                    
                    ct_row += "<td>" + arr_result.key              + "</td>";
                    ct_row += "<td>" + arr_result.subject          + "</td>";
                    ct_row += "<td>" + arr_result.category_name    + "</td>";
                    ct_row += "<td>" + arr_result.price            + " VNĐ</td>";
                    ct_row += "<td>" + arr_result.vat              + "</td>";
                    ct_row += "<td>" + arr_result.insert           + "</td>";

                    $("#tr_"+i_key).html(ct_row);

                    $("#tr_"+i_key).css("background-color","#FFFFFF");

                    $("#dialog_excute").dialog("close");
                    $("#dialog_notice").dialog("close");

                }
                else if (i_key == 0 && arr_result.result == 1)
                {
                    alert("Thêm Thành Công");
                    $("#dialog_excute").dialog("close");
                    call_edit_page(0);
                }
            },
            error: function (){
                alert('Trang hiện hành không tồn tại.');
                $("#dialog_excute").dialog("close");
            }
        });//End Ajax
    }//End if (bool_submit == true)

    return false;
});//End form submit


function ajaxFileUpload()
{
    var urlAction = "<?=Yii::app()->createUrl("product/UploadImage");?>";
    
    $.ajaxFileUpload ({
        url                : urlAction,
        secureuri        : false,
        fileElementId    : "file_image",
        dataType        : "json",
        data:{
            id_item          : "id",
            url_image        : "images/image_product",
            fileInputName    : "file_image",
            width_image      : 0,
            height_image     : 120
        },
        success: function (data, status)
        {
            if(typeof(data.error) != "undefined")
            {
                alert(data.error);
            }
            else
            {
                var url_image = "<?=Yii::app()->baseUrl;?>/" + data.result;
                $("#img_preview").attr("src", url_image);
            }
        },
        error: function (data, status, e)
        {
            alert(e);
        }
    });
    
    return false;
}//end ajaxFileUpload(urlAction)

/* ==================================================
* @Method:    visible_uploadMultibox
* @Describe:  display upload multi image to server or
*             images from another server
* @return:    void
* =================================================== */
function visible_uploadMultibox()
{
    if(document.getElementById("chk_Multiimage").checked == true)
    {
        $("#div_addMultiImage").hide();
        $("#div_addMultiURLImage").show();
    }
    else
    {
        $("#div_addMultiImage").show();
        $("#div_addMultiURLImage").hide();
    }
}//End visible_uploadbox

/* ==================================================
* @Method:    add_ImageToPrepareArea
* @Describe:  Add selected image to prepare area
*             to user check last time and add these images to server
* @return:    void
* =================================================== */
function add_ImageToPrepareArea (s_imageURL, s_imageName, i_methodUpload)
{
    i_imgCount += 1;

    var ct  = '<div class = "item_vertical" id="div_img'+ i_imgCount +'">';
    ct     += '<img name="img_upload" alt = "'+ s_imageName +'" src = "'+ s_imageURL +'" />';
    ct     += '<div class="item_content border_radius_all">';
    ct     += '<input id="btn_delete" name="delete" type="button" value="Xóa" style="width:100%;" class="button button_css3" onclick="delete_selectedItem(\'div_img'+ i_imgCount +'\', '+ i_methodUpload +', 0)" />';
    ct     += '<span></span>';
    ct     += '</div>';
    ct     += '</div><!-- End item_vertical -->';

    $("div#div_galleriesImage").append(ct);
}//End add_ImageToPrepareArea

/* ==================================================
 * @Method:    $("input#btn_saveImage").click
 * @Describe:  save selected images to website
 * @return:    boolean
 * =============================================== */
function delete_selectedItem(s_idDiv, i_uploadMethod, i_itemKey)
{
    if ( s_idDiv == "" )
    {
        alert("This image don't have file name to remove, please refresh and add image again.");
        return false;
    }
    else if ( s_idDiv != "" && i_uploadMethod == 1 )
    {
        //Upload images from another server
        $("div#"+s_idDiv).remove();
    }
    else if ( s_idDiv != "" && i_uploadMethod == 2 )
    {
        $.ajax({
            url         : "<?=Yii::app()->createUrl("product/DeleteFile")?>",
            type        : "POST",
            contentType : "application/x-www-form-urlencoded; charset=UTF-8",
            cache       : false,
            data        : {
                item_key     : i_itemKey,
                s_imgName    : $("div#"+s_idDiv).children().attr("alt")
            },
            success     : function(string){ 
                if(string==1)
                    $("div#"+s_idDiv).remove();
                else
                    alert(string);
            },
            error       : function (){alert('Trang hiện hành không tồn tại.');}
        });//End Ajax
    }//End else if

    return true;
}
</script>